package com.cskaoyan.service.wx_goods;

import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.PageDataVo;
import com.cskaoyan.bean.configmanagement.WX;
import com.cskaoyan.bean.goods.*;
import com.cskaoyan.bean.mall.brand.Brand;
import com.cskaoyan.bean.mall.brand.BrandExample;
import com.cskaoyan.bean.mall.issue.Issue;
import com.cskaoyan.bean.mall.issue.IssueExample;
import com.cskaoyan.bean.user.CollectExample;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.bean.wx_goods.*;
import com.cskaoyan.bean.wx_goods.Category;
import com.cskaoyan.bean.wx_goods.CategoryExample;
import com.cskaoyan.bean.wx_home.WxGoods;
import com.cskaoyan.mapper.configmanagement.ConfigManagementMapper;
import com.cskaoyan.mapper.goods.*;
import com.cskaoyan.mapper.mall.BrandMapper;
import com.cskaoyan.mapper.mall.IssueMapper;
import com.cskaoyan.mapper.user.CollectMapper;
import com.cskaoyan.mapper.wx_goods.WxCategoryMapper;
import com.cskaoyan.utils.MarketPageUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @description:
 * @author: enhui
 **/
@Service
public class WxGoodsServiceImpl implements WxGoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    WxCategoryMapper categoryMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    IssueMapper issueMapper;
    @Autowired
    CollectMapper collectMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    ConfigManagementMapper configMapper;
    private String market_wx_share = "market_wx_share";


    @Override
    public int goodsCount() {
        GoodsExample goodsExample = new GoodsExample();
        int count = (int) goodsMapper.countByExample(goodsExample);
        return count;
    }

    @Override
    public WxGoodsCategoryVO getGoodsByCategory(Integer id) {
        WxGoodsCategoryVO categoriesVO = new WxGoodsCategoryVO();
        //查询这个id对应的level或pid，进行区分
        Category category = categoryMapper.selectByPrimaryKey(id);
        Integer pid = category.getPid();
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        //当前id为一个父级的id，从父级category进入
        if (pid == 0) {
            categoriesVO.setParentCategory(category);
            criteria.andPidEqualTo(id);
            //查询取出第一个放入当前currentCategory，同级所有的放入brotherCategory
            List<Category> categories = categoryMapper.selectByExample(categoryExample);
            categoriesVO.setCurrentCategory(categories.get(0));
            categoriesVO.setBrotherCategory(categories);
        } else {
            //id是当前category
            categoriesVO.setCurrentCategory(category);
            //查询兄弟，不需要排除自己
            criteria.andPidEqualTo(pid);
            List<Category> brotherCategories = categoryMapper.selectByExample(categoryExample);
            categoriesVO.setBrotherCategory(brotherCategories);
            //查找父类
            CategoryExample categoryExampleForParent = new CategoryExample();
            criteria.andIdEqualTo(pid);
            List<Category> categories = categoryMapper.selectByExample(categoryExampleForParent);
            categoriesVO.setParentCategory(categories.get(0));
        }
        return categoriesVO;
    }

    @Override
    public WxGoodsListPageVO goodsList(String keyword, Integer brandId, Integer categoryId, BaseParam param) {
        MarketPageUtil.startPage(param);
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria categoryExampleCriteria = categoryExample.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andNameLike("%" + keyword + "%");
            categoryExampleCriteria.andNameLike("%" + keyword + "%");
        }
        if (categoryId != null) {
//            criteria.andCategoryIdEqualTo(categoryId);
            if (categoryId != 0) {
                criteria.andCategoryIdEqualTo(categoryId);
            }
        }
        if (brandId != null) {
            criteria.andBrandIdEqualTo(brandId);
        }
        if (!StringUtils.isEmpty(param.getSort())) {
            goodsExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        }
        List<WxGoods> wxGoods = goodsMapper.selectWXGoodsByExample(goodsExample);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        return WxGoodsListPageVO.ok(wxGoods, categories);
    }

    @Override
    public WxGoodsDetailVO goodsDetail(Integer id, HttpServletRequest httpServletRequest) {
        WxGoodsDetailVO wxGoodsDetailVO = new WxGoodsDetailVO();
        //根据goodsId查规格表specificationList
        List<SpecificationVO> specificationVOList = new ArrayList<>();
        //查询所有的规格，多条数据，只取出规格类型，去重
        Set<String> specificationNames = goodsSpecificationMapper.selectSpecificationListByGoodsId(id);
        for (String specificationName : specificationNames) {
            SpecificationVO specificationVO = new SpecificationVO();
            //取出规格specification的名字，同一名字对应多条数据
            specificationVO.setName(specificationName);
            //每次循环重新查，根据goodId和specification
            GoodsSpecificationExample example = new GoodsSpecificationExample();
            GoodsSpecificationExample.Criteria exampleCriteria = example.createCriteria();
            exampleCriteria.andGoodsIdEqualTo(id).andSpecificationEqualTo(specificationName);
            //查询同一id商品的同一规格名下的不同规格，比如颜色下的多个颜色
            List<GoodsSpecification> goodsSpecificationsSameSpecificationName = goodsSpecificationMapper.selectByExample(example);
            specificationVO.setValueList(goodsSpecificationsSameSpecificationName);
            specificationVOList.add(specificationVO);
        }
        wxGoodsDetailVO.setSpecificationList(specificationVOList);

        //查询issue
        List<Issue> issues = issueMapper.selectByExample(new IssueExample());
        wxGoodsDetailVO.setIssue(issues);

        //根据type=0、商品id、用户id查询是否被收藏
        Integer userHasCollect = 0;
        try {
            User user = (User) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
            CollectExample collectExample = new CollectExample();
            CollectExample.Criteria collectExampleCriteria = collectExample.createCriteria();
            collectExampleCriteria.andUserIdEqualTo(user.getId()).andTypeEqualTo((byte) 0).andValueIdEqualTo(id);
            long count = collectMapper.countByExample(collectExample);
            if (count == 1) {
                userHasCollect = 1;
            }
        } catch (Exception e) {
            //用户没有登录
            wxGoodsDetailVO.setUserHasCollect(0);
        }
        wxGoodsDetailVO.setUserHasCollect(userHasCollect);

        //查询评论，按最新的排序吧，设置显示2个，暂时在sql语句中写死
        //先根据type=0、商品id查询总的评论数量
        CommentExample commentExample = new CommentExample();
        CommentExample.Criteria commentExampleCriteria = commentExample.createCriteria();
        commentExampleCriteria.andTypeEqualTo((byte) 0).andValueIdEqualTo(id);
        long count = commentMapper.countByExample(commentExample);
        WxCommentVO wxCommentVO = new WxCommentVO();
        wxCommentVO.setCount((int) count);
        List<WxCommentData> wxCommentData = new ArrayList<>();
        if (count != 0) {
            wxCommentData = commentMapper.selectByGoodsId(id);
        }
        wxCommentVO.setData(wxCommentData);
        wxGoodsDetailVO.setComment(wxCommentVO);

        //商品参数goodsAttributes
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        GoodsAttributeExample.Criteria goodsAttributeExampleCriteria = goodsAttributeExample.createCriteria();
        goodsAttributeExampleCriteria.andGoodsIdEqualTo(id);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);
        wxGoodsDetailVO.setAttribute(goodsAttributes);

        //商品货品表
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria productExampleCriteria = goodsProductExample.createCriteria();
        productExampleCriteria.andGoodsIdEqualTo(id);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        wxGoodsDetailVO.setProductList(goodsProducts);

        //goods
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        wxGoodsDetailVO.setInfo(goods);

        //品牌
        Brand brand = brandMapper.selectByPrimaryKey(goods.getBrandId());
        wxGoodsDetailVO.setBrand(brand);

        //分享
        Boolean share = Boolean.valueOf(configMapper.selectByName(market_wx_share));
        wxGoodsDetailVO.setShare(share);
        return wxGoodsDetailVO;
    }

    /**
     * 相关商品推荐
     * 这里先推荐同一个类别下的除自己以外的商品，推荐的个数设置为6个，顺序为id的逆序
     * 有想法的可以加
     *
     * @param id
     * @return
     */
    @Override
    public PageDataVo goodsRelated(Integer id) {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setOrderByClause("id desc limit 6");
        GoodsExample.Criteria goodsExampleCriteria = goodsExample.createCriteria();
        goodsExampleCriteria.andIdNotEqualTo(id).andCategoryIdEqualTo(goods.getCategoryId());
        List<WxGoods> goodsRelated = goodsMapper.selectWXGoodsByExample(goodsExample);

        return PageDataVo.ok(goodsRelated);
    }
}
